import path from "path";
import fs from "fs";

function getRouters(apptsx: string) {
  // 自动从 App.tsx 中提取 Route path
  const appTsxPath = path.resolve(apptsx);
  const appContent = fs.readFileSync(appTsxPath, "utf-8");

  // 匹配 <Route path="xxx" ...>，捕获 path 属性
  const routePathRegex = /<Route\s+[^>]*path=["']([^"']+)["']/g;
  const ROUTERS = [];
  let match;
  while ((match = routePathRegex.exec(appContent)) !== null) {
    // 只收集非空 path
    if (match[1] && match[1] !== "") {
      // 确保以 / 开头
      let route = match[1].startsWith("/") ? match[1] : "/" + match[1];
      ROUTERS.push(route);
    }
  }
  return ROUTERS;
}

/**
 * 创建单页面应用的路由文件
 * @param root 根目录
 * @param appTsx App.tsx 文件路径 默认 ./src/App.tsx
 */
export default function spar(root: string, appTsx: string = "./src/App.tsx") {
  const indexHtml = path.join(root, "index.html");
  if (!fs.existsSync(indexHtml)) {
    throw new Error("index.html not found");
  }
  const routers = getRouters(appTsx);
  routers.forEach(async (router) => {
    const routerPath = path.join(root, router.replace(/\/\*/g, ""));
    const routerIndexHtml = path.join(routerPath, "index.html");
    if (!fs.existsSync(routerPath)) {
      fs.mkdirSync(routerPath, { recursive: true });
    }
    fs.copyFileSync(indexHtml, routerIndexHtml);
  });
}
